<template>
  <el-drawer
    v-model="props.processTracingVisible"
    title="流程追踪"
    :with-header="false"
    @close="onClose"
    size="calc(100vw - 252px)"
  >
    <div class="processtracing">
      <div class="header">
        <el-steps
          :active="parseInt(props.mainForm.value.repAcceptState)"
          finish-status="process"
          align-center
          :style="{ 'margin-top': '64px', heihgt: '200px' }"
        >
          <el-step
            :title="item"
            :key="index"
            v-for="(item, index) in stepData"
            :icon="
              parseInt(props.mainForm.value.repAcceptState) >= index
                ? SuccessFilled
                : ''
            "
          ></el-step>
        </el-steps>
      </div>
      <div class="title">报修详情</div>
      <el-divider />
      <div class="content">
        <el-form
          :inline="true"
          :model="props.mainForm.value"
          class="demo-form-inline"
          ref="mainDetail"
        >
          <el-row>
            <el-col :span="8">
              <el-form-item label="维修名称：">
                {{ props.mainForm.value.repName }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="上报单位：">
                {{ props.mainForm.value.creator.organName }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="上报人：">
                {{ props.mainForm.value.creator.name }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="联系电话：">
                {{ props.mainForm.value.creator.phone }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="上报时间：">
                {{ props.mainForm.value.createTime }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="紧急情况：">
                <span v-if="props.mainForm.value.urgency === '1'">非常紧急</span>
                <span v-else-if="props.mainForm.value.urgency === '2'">一般紧急</span>
                <span v-else-if="props.mainForm.value.urgency === '3'">一般</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="航站楼：">
                {{ props.mainForm.value.terminal }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="楼层：">
                {{ props.mainForm.value.eqptFloor }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <!-- <el-form-item label="位置：">
                <el-icon
                  @click="
                    () => {
                      mapVisible = !mapVisible;
                    }
                  "
                  :style="{ marginRight: '10px' }"
                >
                  <Position />
                </el-icon>
                <map-control
                  @mapLoad="mapLoadEvent"
                  @mapClick="mapClick"
                  v-if="mapVisible"
                  :style="{ width: '90%' }"
                ></map-control>
              </el-form-item> -->
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="设备类型：">
                {{ props.mainForm.value.typeName }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="问题类型：">
                {{ props.mainForm.value.problemType }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="问题描述：">
                {{ props.mainForm.value.problemDesc }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="图片：">
                <el-image
                  style="width: 100px; height: 100px"
                  v-for="item in props.mainForm.value.files"
                  :src="item.resourceAddress"
                ></el-image>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="备注：">
                {{ props.mainForm.value.remarks }}
              </el-form-item>
            </el-col>
            <el-col :span="8"></el-col>
            <el-col :span="8"></el-col>
          </el-row>
        </el-form>
      </div>
      <el-divider />
      <div class="footer">
        <el-button type="info" plain @click="onClose">取消</el-button>
        <el-button type="danger" plain @click="handleReject">驳回</el-button>
        <el-button type="warning" plain @click="handleSuspend">挂起</el-button>
        <el-button
          type="primary"
          plain
          @click="handleAssign"
          :disabled="parseInt(props.mainForm.value.repAcceptState) >= 1"
          >指派</el-button
        >
      </div>
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle?.[dialogTitleCategory]"
        width="30%"
        :show-close="false"
        class="elDialog"
        :destroy-on-close="true"
        @close="handleClose"
      >
        <el-form :model="dialogForm" ref="dialogDetail">
          <div v-if="dialogTitleCategory == 'reject'">
            <el-form-item label="审批意见:">
              <el-input
                type="textarea"
                v-model="dialogForm.reject.nodeContent.reject"
              ></el-input>
            </el-form-item>
          </div>

          <div v-if="dialogTitleCategory == 'suspend'">
            <el-form-item label="挂起原因:">
              <el-input
                type="textarea"
                v-model="dialogForm.suspend.nodeContent.suspend"
              ></el-input>
            </el-form-item>
          </div>
          <div v-if="dialogTitleCategory == 'assign'">
            <el-form-item label="维修人员:">
              <el-select
                v-model="dialogForm.assign.nodeContent.serviceman"
                :style="{ width: '100%', marginLeft: '2px' }"
              >
                <el-option
                  v-for="item in memberPeopelData"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="计划完成时间:">
              <el-date-picker
                v-model="dialogForm.assign.nodeContent.planCompleteTime"
                type="datetime"
                placeholder="选择日期时间"
                :style="{ width: '100%', marginLeft: '2px' }"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="维修员需在">
              <el-date-picker
                v-model="dialogForm.assign.nodeContent.planAcceptTime"
                type="datetime"
                placeholder="选择日期时间"
                :style="{ width: '80%', marginLeft: '2px' }"
              >
              </el-date-picker>
              之前接受任务
            </el-form-item>
            <el-form-item label="逾期">
              <el-input
                :style="{ width: '20%', marginLeft: '2px' }"
                v-model="dialogForm.assign.nodeContent.overdue2.unit"
              ></el-input>
              <el-select
                v-model="dialogForm.assign.nodeContent.overdue2.time"
                :style="{ width: '20%', marginLeft: '2px' }"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              未接受，为
              <el-select
                v-model="dialogForm.assign.nodeContent.overdue2.degree"
                :style="{ width: '40%', marginLeft: '2px' }"
              >
                <el-option
                  v-for="item in degreeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="逾期">
              <el-input
                :style="{ width: '20%', marginLeft: '2px' }"
                v-model="dialogForm.assign.nodeContent.overdue1.unit"
              ></el-input>
              <el-select
                v-model="dialogForm.assign.nodeContent.overdue1.time"
                :style="{ width: '20%', marginLeft: '2px' }"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              未接受，为
              <el-select
                v-model="dialogForm.assign.nodeContent.overdue1.degree"
                :style="{ width: '40%', marginLeft: '2px' }"
              >
                <el-option
                  v-for="item in degreeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="紧急程度">
              <span :style="{ paddingLeft: '20px' }">紧急 - 优先级高</span>
            </el-form-item>
            <el-form-item label="故障分析">
              <el-upload
                v-model:file-list="dialogForm._faultAnalysisList"
                class="upload-demo"
                action="#"
                multiple
                name="file"
                :before-upload="beforeUpload"
                :http-request="(option:any) => uploadAction(option,true)"
              >
                <el-button :style="{ marginRight: '20px' }">选择文件</el-button>
                <span
                  v-if="
                    dialogForm.assign.nodeContent.faultAnalysisList.length == 0
                  "
                  >未选择任何文件</span
                >
                <a
                  href="#blank"
                  :style="{ display: 'block', marginLeft: '20px' }"
                  >从知识库中选择</a
                >
              </el-upload>
            </el-form-item>
            <el-form-item label="维修方案">
              <el-upload
                v-model:file-list="dialogForm._maintenancePlanList"
                class="upload-demo"
                action="#"
                multiple
                name="file"
                :before-upload="beforeUpload"
                :http-request="(option:any) => uploadAction(option,false)"
              >
                <el-button :style="{ marginRight: '20px' }">选择文件</el-button>
                <span
                  v-if="
                    dialogForm.assign.nodeContent.maintenancePlanList.length ==
                    0
                  "
                  >未选择任何文件</span
                >
                <a
                  href="#blank"
                  :style="{ display: 'block', marginLeft: '20px' }"
                  >从知识库中选择</a
                >
              </el-upload>
            </el-form-item>
          </div>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="handleClose">取消</el-button>
            <el-button type="primary" @click="handleSubmit">{{
              submitBtnText
            }}</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </el-drawer>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from "vue";
import mapControl from "@/components/map/index.vue";
import { store as mapStore } from "@/components/map/mapStore";
import { image } from "@/assets/index";
import {
  repairReject,
  repairSuspend,
  repairAssign,
} from "@/api/maintenance/repairacceptancemanagement/services";
import { SuccessFilled, Picture, Upload } from "@element-plus/icons-vue";
import { options, degreeOptions } from "./config/utils";
import { ElMessage, UploadRawFile } from "element-plus";
import { useStore } from "vuex";
import { uploadFiles } from "@/api/common";
import { memberPeopelData } from "./config/options";
interface ElDrawerProps {
  processTracingVisible?: boolean;
  mainForm?: any;
}

const stepData = [
  "01 发起报修",
  "02 指派报修",
  "03 报修接收",
  "04 维修完成",
  "05 报修检查",
  "06 报修维修完结",
];
const store = useStore();
const Users = computed(() => store.getters["user/getUserInfo"]);
// 用于保存地图坐标及相关信息
const mapPoint = ref({});
const mapLoadEvent = () => {
  // 向地图添加临时图层
  const clickLayer = mapStore.BNMap.creatGraphicsLayer({ id: "clickLayer" });
  clickLayer.removeAll();
  const point = mapStore.BNMap.createPoint({
    x: props.mainForm.value.coordinate.latitude,
    y: props.mainForm.value.coordinate.longitude,
    spatialReference: mapStore.BNMap.spatialReference,
    // spatialReference: props.mainForm.value.coordinate.spatialReference,
  });
  mapStore.BNMap.setCenter(point);
  const symbolStyle = mapStore.BNSymbol.PictureMarkerSymbol(
    image.point,
    20,
    25
  );
  // 创建要素
  const picgraphic = mapStore.BNMap.graphic(point, symbolStyle);
  // 添加到地图
  clickLayer.add(picgraphic);
};
// 地图点击事件--本页面暂未使用，留着备份
const mapClick = (evt: any) => {
  console.log(evt.mapPoint.x, evt.mapPoint.y);
  // 点位坐标 longitude：evt.mapPoint.x  latitude：evt.mapPoint.y
  // 区域字段在地图数据中暂时没有
  // 移除临时图层
  mapStore.BNMap.removeGraphicsLayer("clickLayer");
  // 向地图添加临时图层
  const clickLayer = mapStore.BNMap.creatGraphicsLayer({ id: "clickLayer" });
  clickLayer.removeAll();
  // 创建点
  const point = mapStore.BNMap.createPoint({
    x: evt.mapPoint.x,
    y: evt.mapPoint.y,
    spatialReference: evt.mapPoint.spatialReference,
  });
  mapStore.BNMap.setCenter(point);
  // 创建图片
  const symbolStyle = mapStore.BNSymbol.PictureMarkerSymbol(
    image.point,
    20,
    25
  );
  // 创建要素
  const picgraphic = mapStore.BNMap.graphic(point, symbolStyle);
  // 添加到地图
  clickLayer.add(picgraphic);
  mapStore.BNMap.addGraphicsLayer(clickLayer);
  // 将相关信息保存到变量
  mapPoint.value.x = evt.mapPoint.x;
  mapPoint.value.y = evt.mapPoint.y;
  // 地图区域值暂时为空
};
const mapVisible = ref(false);
const dialogForm = reactive({
  reject: { nodeContent: { reject: "" } },
  suspend: { nodeContent: { suspend: "" } },
  assign: {
    nodeContent: {
      serviceman: "",
      planCompleteTime: "",
      planAcceptTime: "",
      overdue1: {
        time: "",
        unit: "",
        degree: "",
      },
      overdue2: {
        time: "",
        unit: "",
        degree: "",
      },
      faultAnalysisList: <any>[],
      maintenancePlanList: <any>[],
    },
  },
  _faultAnalysisList: <any>[],
  _maintenancePlanList: <any>[],
});
const dialogVisible = ref(false);
const dialogTitleCategory: any = ref("reject");
const dialogTitle: any = {
  reject: "驳回",
  suspend: "挂起",
  assign: "责任单位接受并指派",
};
const props = defineProps<ElDrawerProps>();
console.log(props)
const emit = defineEmits(["close", "getListData"]);
const handleClose = () => {
  (dialogForm.reject = { nodeContent: { reject: "" } }),
    (dialogForm.suspend = { nodeContent: { suspend: "" } }),
    (dialogForm.assign = {
      nodeContent: {
        serviceman: "",
        planCompleteTime: "",
        planAcceptTime: "",
        overdue1: {
          time: "",
          unit: "",
          degree: "",
        },
        overdue2: {
          time: "",
          unit: "",
          degree: "",
        },
        faultAnalysisList: <any>[],
        maintenancePlanList: <any>[],
      },
    }),
    (dialogForm._faultAnalysisList = []);

  dialogForm._maintenancePlanList = [];
  dialogVisible.value = false;
};
const lastMender = computed(() => {
  return {
    id: Users.value?.userId,
    name: Users.value?.userName,
    phone: Users.value?.phone,
    organId: Users.value?.organId,
    organName: Users.value?.organName,
  };
});

const handleSubmit = async () => {
  try {
    if (dialogTitleCategory.value == "reject") {
      const res = await repairReject({
        ...props.mainForm.value,
        mender: lastMender.value,
        nodeContent: dialogForm.reject.nodeContent,
      });
    }
    if (dialogTitleCategory.value == "suspend") {
      await repairSuspend({
        ...props.mainForm.value,
        mender: lastMender.value,
        nodeContent: dialogForm.suspend.nodeContent,
      });
    }
    if (dialogTitleCategory.value == "assign") {
      await repairAssign({
        ...props.mainForm.value,
        mender: lastMender.value,
        nodeContent: dialogForm.assign.nodeContent,
      });
    }
    ElMessage.success("操作成功");
    return onClose();
  } catch (error: any) {
    ElMessage.error(error.message);
  }
};
const onClose = () => {
  mapVisible.value = false;
  (dialogForm.reject = { nodeContent: { reject: "" } }),
    (dialogForm.suspend = { nodeContent: { suspend: "" } }),
    (dialogForm.assign = {
      nodeContent: {
        serviceman: "",
        planCompleteTime: "",
        planAcceptTime: "",
        overdue1: {
          time: "",
          unit: "",
          degree: "",
        },
        overdue2: {
          time: "",
          unit: "",
          degree: "",
        },
        faultAnalysisList: <any>[],
        maintenancePlanList: <any>[],
      },
    }),
    (dialogForm._faultAnalysisList = []);

  dialogForm._maintenancePlanList = [];
  dialogVisible.value = false;
  dialogTitleCategory.value = "reject";
  emit("close");
  emit("getListData");
};
const handleReject = () => {
  dialogTitleCategory.value = "reject";
  dialogVisible.value = true;
};
const handleSuspend = () => {
  dialogTitleCategory.value = "suspend";
  dialogVisible.value = true;
};
const handleAssign = () => {
  dialogTitleCategory.value = "assign";
  dialogVisible.value = true;
};
const beforeUpload = (file: UploadRawFile) => {
  const isAllowedExtension =
    /\.(jpg|jpeg|png|gif|xls|xlsx|doc|docx|ppt|pptx|pdf)$/i.test(file.name);
  const isAllowedSize = file.size / 1024 / 1024 < 100;
  if (!isAllowedExtension) {
    ElMessage.error("只允许上传图片、Excel、Word、PPT和PDF格式的文件");
  }
  if (!isAllowedSize) {
    ElMessage.error("文件大小不能超过100M");
  }
  return isAllowedExtension && isAllowedSize;
};
const uploadAction = (option: any, isFaultAnalysis: boolean) => {
  const type = isFaultAnalysis ? "faultAnalysisList" : "maintenancePlanList";
  let param = new FormData();
  param.append("file", option.file);
  param.append("fileName", option.filename);
  uploadFiles(param).then((res: any) => {
    if (res && res.code == 1) {
      dialogForm.assign.nodeContent?.[type].push({
        enclosureContent: res.data.enclosureContent,
        enclosureName: res.data.enclosureName,
        enclosureSuffix: res.data.enclosureSuffix,
        resourceAddress: res.data.resourceAddress,
        enclosureCode: res.data.enclosureCode,
      });
      ElMessage.success("上传成功！");
    } else {
      if (res && res.msg) {
        ElMessage.error(res.msg);
      } else {
        ElMessage.error("上传失败！");
      }
    }
  });
};
const submitBtnText = computed(() => {
  if (dialogTitleCategory.value == "reject") return "驳回";
  if (dialogTitleCategory.value == "suspend") return "挂起";
  return "确认指派";
});
</script>

<style lang="less" scoped>
.processtracing {
  height: 96%;
  display: flex;
  flex-direction: column;
  .header {
    height: 200px;
    :deep(.el-steps) {
      .el-step__head {
        border-color: #4d7fcd;
        height: 28px;
      }
      .el-step__line {
        width: 80%;
        margin-left: 10%;
        background-color: #4d7fcd;
      }
      .el-icon svg {
        color: #4d7fcd;
      }
      .el-step__head.is-wait .el-step__icon .el-step__icon-inner {
        opacity: 0;
        font-size: -1px;
      }
      .el-step__title {
        position: absolute;
        top: -44px;
        left: 94px;
      }
      .el-step.is-center .el-step__description {
        padding-top: 10px;
      }
    }
  }
  /deep/.el-step__icon {
    font-size: 2rem;
  }
  .title {
    height: 16px;
    line-height: 16px;
    font-size: 16px;
  }
  .title:before {
    content: "";
    display: inline-block;
    width: 3px;
    height: 14px;
    background-color: #4d7fcd;
    margin-left: -20px;
    margin-right: 20px;
    vertical-align: middle;
  }
  .content {
    flex: 1;
  }
  .footer {
    height: 40px;
    display: flex;
    justify-content: center;
  }
}
</style>
